package utils;

import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * 使用连接池连接数据库
 * @author zhrb
 */
public class JdbcUtil {
	
	public static Connection conn = null;
	public static JdbcUtil instance = null;
	
	// 连接池的核心类
	public static ComboPooledDataSource dataSource;
	
	//初始化连接池相关参数
	static{
		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setDriverClass(PropertiesUtil.getValue("jdbcName"));
			dataSource.setJdbcUrl(PropertiesUtil.getValue("dbUrl"));
			dataSource.setUser(PropertiesUtil.getValue("dbUserName"));
			dataSource.setPassword(PropertiesUtil.getValue("dbPassword"));
			dataSource.setInitialPoolSize(5);
			dataSource.setMinPoolSize(5);
			dataSource.setMaxPoolSize(10);
			// 以下两句用于设置自动重连
			dataSource.setIdleConnectionTestPeriod(10);
			dataSource.setTestConnectionOnCheckin(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	
	// 单例模式:得到ConnectionManager实例。用户只能通过该方法获得DbUtil实例
	/*public static final DbUtil getInstance() {
		if(instance == null){
			try {
				instance = new DbUtil();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return instance;
	}*/
	
	// 获取连接
	public static synchronized Connection getCon(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	//jdk1.7的AutoCloseable语法
	/**
	 * 如需同时关闭statement, resultset与connection，请依次按顺序关闭，即按照s->r->c的顺序将参数放入closeAll
	 * @param obj
	 */
	public static void closeAll(AutoCloseable... obj) {
		for (AutoCloseable item : obj) {
			try {
				if(item!=null){
					item.close();
				}
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}
}